#include "urltxtwidget.h"
#include <QDebug>
#include <QFile>
#include <QXmlStreamReader>
#include <QTextEdit>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QList>
#include <QMimeData>
#include <QUrl>
#include <QHBoxLayout>
#include <QPushButton>
#include <QFileInfo>
#include <QGridLayout>
#include <QTextStream>

UrlTxtWidget::UrlTxtWidget(QWidget *parent)
    : QWidget(parent)
{
    CreateUi();
    UpdateText();

    setAcceptDrops(true);
    resize(800, 600);
}

UrlTxtWidget::~UrlTxtWidget()
{

}

static bool urlFilter(const QString& url)
{
    int pos = url.lastIndexOf('.');
    if (pos != -1)
    {
        QString ref = url.mid(pos);
        if (ref.compare(".JPG", Qt::CaseInsensitive)==0 ||
            ref.compare(".PNG", Qt::CaseInsensitive)==0 ||
            ref.compare(".GIF", Qt::CaseInsensitive)==0 ||
            ref.compare(".JPEG", Qt::CaseInsensitive)==0 ||
            ref.compare(".BMP", Qt::CaseInsensitive)==0 ||
            ref.compare(".JS", Qt::CaseInsensitive)==0 ||
            ref.compare(".CSS", Qt::CaseInsensitive)==0 ||
            ref.compare(".SWF", Qt::CaseInsensitive)==0)
        {
            return false;
        }
    }
    return true;
}

void UrlTxtWidget::slotExport()
{
    QString filename = windowTitle();

    int pos = filename.lastIndexOf('.');
    if (pos != -1)
    {
        filename.replace(pos, 4, ".txt");
        QFile file(filename);
        if (file.open(QFile::WriteOnly))
        {
            QTextStream ts(&file);
            ts << m_pEdt->toPlainText();
        }
    }
 }

void UrlTxtWidget::slotBatchMode(bool bDown)
{
    m_pBtnExport->setEnabled(!bDown);
    m_pEdt->clear();
}

void UrlTxtWidget::CreateUi()
{
    m_pEdt = new QTextEdit();
    QGridLayout* pLayOut = new QGridLayout();
    m_pBtnExport = new QPushButton();
    m_pBtnBatch = new QPushButton();
    m_pBtnBatch->setCheckable(true);
    connect(m_pBtnExport, SIGNAL(clicked()), this, SLOT(slotExport()));
    connect(m_pBtnBatch, SIGNAL(toggled(bool)), this, SLOT(slotBatchMode(bool)));

    pLayOut->addWidget(m_pEdt, 0, 0, 8, 1);
    pLayOut->addWidget(m_pBtnExport, 0, 1);
    pLayOut->addWidget(m_pBtnBatch, 1, 1);
    setLayout(pLayOut);
}

void UrlTxtWidget::UpdateText()
{
    m_pBtnExport->setText(tr("&Export"));
    m_pBtnBatch->setText(tr("&Batch Mode"));
}

void UrlTxtWidget::ParseSiteFiles(QXmlStreamReader& xml, QStringList& list)
{
    QXmlStreamReader::TokenType token = xml.readNext();
    QXmlStreamReader::TokenType lastToken = token;
    while (true)
    {
        if (xml.name() == "FullURL")
        {
            list << xml.readElementText();
        }
        else if(xml.name() == "Inputs")
        {
            ParseInputsUrl(xml, list);
        }
        lastToken = token;
        token = xml.readNext();
        if (token == xml.EndElement)
        {
            //<NAME></NAME> 空元素
            if (lastToken!=xml.StartElement)
            {
                break;
            }
        }
    }
}

void UrlTxtWidget::ParseVariation(QXmlStreamReader& xml, QStringList& list)
{
    QXmlStreamReader::TokenType token = xml.readNext();
    while (token != xml.EndElement)
    {
        if (xml.name() == "URL")
        {
            QString url = xml.readElementText();

            if (url.contains("SaveNetBook.asp"))
            {
                int a =0 ;
                a++;
            }
            while (token != xml.EndElement)
            {
                token = xml.readNext();
                if (token == xml.Characters && xml.isCDATA())
                {
                    QStringRef urlParam = xml.text();
                    url += "?";
                    url += urlParam.toString();
                    list << url;
                    return;
                }
            }
            list << url;
            return;
        }
        token = xml.readNext();
    }
}

void UrlTxtWidget::ParseInputsUrl(QXmlStreamReader& xml, QStringList& list)
{
    QXmlStreamReader::TokenType token = xml.readNext();
    while (token != xml.EndElement)
    {
        if (xml.name() == "URL")
        {
            list << xml.readElementText();
        }
        token = xml.readNext();
    }
}

static void skipUnknownElement(QXmlStreamReader& reader)
{
    reader.readNext();
    while (!reader.atEnd())
    {
        if (reader.isEndElement())
        {
            reader.readNext();
            break;
        }
        if (reader.isStartElement())
        {
            skipUnknownElement(reader);
        }
        else
        {
            reader.readNext();
        }
    }
}

bool UrlTxtWidget::Conver2Txt(const QString& xmlFileName, const QString& txtFileName)
{
    QStringList list;
    if (!ParseCwlXml(xmlFileName, list))
    {
        return false;
    }

    {
        QFile file(txtFileName);
        if (file.open(QFile::WriteOnly))
        {
            QTextStream ts(&file);
            foreach (QString url, list)
            {
                ts << url << "\n";
            }
            return true;
        }
    }

    return false;
}

bool UrlTxtWidget::OpenCwlXml(const QString& xmlFileName)
{
    QFileInfo fileName(xmlFileName);
    QString fileExtend = fileName.suffix();//扩展名
    if (fileExtend.compare("xml", Qt::CaseInsensitive)==0)
    {
        setWindowTitle(xmlFileName);
        m_urlList.clear();
        ParseCwlXml(xmlFileName, m_urlList);
        m_pEdt->clear();

        foreach (QString url, m_urlList)
        {
            if (urlFilter(url))
            {
                QString urlLine = url += "\n";
                m_pEdt->insertPlainText(urlLine);
            }
        }
        return true;
    }
    return false;
}

bool UrlTxtWidget::ParseCwlXml(const QString& xmlFileName, QStringList &list)
{
    QFile file(xmlFileName);
    if (!file.open(QFile::ReadOnly|QFile::Text))
    {
        return false;
    }
    QXmlStreamReader xml(&file);
    while (!xml.atEnd() && !xml.hasError())
    {
        //读取下一个element.
        QXmlStreamReader::TokenType token = xml.readNext();

        //如果获取的仅为StartDocument,则进行下一个
        if (token == QXmlStreamReader::StartDocument)
        {
            continue;
        }

        //如果获取了StartElement,则尝试读取
        if (token == QXmlStreamReader::StartElement)
        {
            if (xml.name() == "FullURL")
            {
                list << xml.readElementText();
            }
            else if (xml.name() == "Variation")
            {
                ParseVariation(xml, list);
            }
        }
    }

    if (xml.hasError())
    {
        //QMessageBox::information(NULL, QString("parseXML"), xml.errorString());
    }

    //从reader中删除所有设备、数据，并将其重置为初始状态
    xml.clear();
    return true;
}

void UrlTxtWidget::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasFormat("text/uri-list"))
        event->acceptProposedAction();
}

void UrlTxtWidget::dropEvent(QDropEvent * event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    if (urls.isEmpty())
        return;
    if (m_pBtnBatch->isChecked())
    {
        foreach(QUrl url, urls)
        {
            QString xmlFileName = url.toLocalFile();
            QString txtFileName = xmlFileName;
            int pos = txtFileName.lastIndexOf('.');
            if (pos==-1)
            {
            }
            else
            {
                QString ref = txtFileName.mid(pos);
                if (0 != ref.compare(".xml", Qt::CaseInsensitive))
                {
                    continue;
                }

                txtFileName.replace(pos, 4, ".txt");
                if (!Conver2Txt(xmlFileName, txtFileName))
                {
                    continue;
                }
            }
        }
    }
    else
    {
        foreach(QUrl url, urls)
        {
            if (OpenCwlXml(url.toLocalFile()))
                break;
        }
    }
}
